package il.technion.cs236369.proxy.communication.http;

import java.io.IOException;
import java.net.Socket;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
/**
 * implementing a client behavior -  send a message to a remote sever using given a connection.
 * @author  itamar talmi 0396055979 itamar.talmi@gmail.com , ofir haviv 300228921 havivi1986@gmail.com
 *
 */
public class HttpProxyClient{
	
	public HttpProxyClient() {	}
	
	/**
	 * sends an http request using the given socket.
	 * @param clientConnection a valid socket
	 * @param conn -  an HTTP connection that will be binded to to clientConnection. closing is it is on the caller.
	 * @param originalRequest - the request to send.
	 * @return the response of the server.
	 * @throws IOException
	 * @throws HttpException
	 */
	public HttpResponse sendRequestToServer(Socket clientConnection, DefaultHttpClientConnection conn, final HttpRequest originalRequest) throws IOException, HttpException {

		try{
			HttpParams params = new SyncBasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, "UTF-8");
			HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
			HttpProtocolParams.setUseExpectContinue(params, true);
	
			HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {});
			HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
			HttpContext context = new BasicHttpContext(null);
	
			context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
			conn.bind(clientConnection, params);
			originalRequest.setParams(params);
			httpexecutor.preProcess(originalRequest, httpproc, context);
	
			return httpexecutor.execute(originalRequest, conn, context);
		}
		catch(Exception e){
			System.err.println("Error while tring to connect the server");
			//System.err.println("Error in HttpProxyClient.sendRequestToServer");
			//e.printStackTrace();
		}
		return null;
	}

}
